import AsyncStorage from "@react-native-async-storage/async-storage"

type storageString = string | null

export default class StorageManager {
    constructor() {

    }
    /**
     * @description: Stores string value for given key
     * @param {string} key
     * @param {string} value
     * @return Promise<void>
     */
    static storeValue = async (key: string, value: string) => {
        try {
            await AsyncStorage.setItem(key, value)
        } catch (error) {
            console.log('Storage Value Error : ', JSON.stringify(error))
        }
    }
    /**
     * @description: Reads a string value for given key
     * @param {string} key
     * @return Promise<[boolean, string]>
     */
    static readValue = async (key: string): Promise<[boolean, string]> => {
        try {
            let value: storageString = await AsyncStorage.getItem(key)
            if (value && value != '') {
                return [true, value]
            } else {
                return [false, '']
            }
        } catch (error) {
            console.log('Read Storage Value Error : ', JSON.stringify(error))
            return [false, '']
        }
    }
    /**
     * @description: Stores object value for given key
     * @param {string} key
     * @param {T} objectValue
     * @return Promise<void>
     */
    static storeObject = async <T>(key: string, objectValue: T) => {
        try {
            const jsonValue = JSON.stringify(objectValue)
            await AsyncStorage.setItem(key, jsonValue)
        } catch (error) {
            console.log('Storage Ojbect Value Error : ', JSON.stringify(error))
        }
    }
    /**
     * @description: Reads object value for given key
     * @param {string} key
     * @return Promise<[boolean, T | null]>
     */
    static readObject = async <T>(key: string): Promise<[boolean, T | null]> => {
        try {
            const jsonValue = await AsyncStorage.getItem(key)
            if (jsonValue != null) {
                return [true, JSON.parse(jsonValue)]
            } else {
                return [false, null]
            }
        } catch (error) {
            console.log('Read Storage Object Value Error : ', JSON.stringify(error))
            return [false, null]
        }
    }
    /**
     * @description: Removes item for a key
     * @param {string} key
     * @return Promise<void>
     */
    static removeItem = async (key: string) => {
        try {
            await AsyncStorage.removeItem(key)
        } catch (error) {
            console.log('Remove Item Error : ', JSON.stringify(error))
        }
    }
    /**
     * @description: Removes whole AsyncStorage data
     * @return Promise<void>
     */
    static clearAll = async () => {
        try {
            await AsyncStorage.clear()
        } catch (error) {
            console.log('Clear All Item Error : ', JSON.stringify(error))
        }
    }
}